<template>
	<div>
		<div class="dialog">
			<div class="input-group">
				<label class="password-label">标题</label>
				<input class="inpok" id="biaoti" type="text" v-model="biaoti" placeholder="简短的标题" />
			</div>
			<div>
				<div class="underline-div"></div>
			</div>
			<div class="input-group">
				<label class="password-label">取消设置</label>
				<!-- <input class="inpok" @click="djhqnr" type="text" style="text-align: right;" value="随时可取消 >" disabled /> -->
				<div class="kaoyb">
					<picker @change="bindPickerChange" :value="index" :range="array">
						<view class="uni-input">{{ array[index] }} <text class="kuoyi">></text></view>
					</picker>
				</div>
			</div>
		</div>

		<div class="yuie">
			<div class="input-group">
				<label class="password-label">预约时段排期设置</label>
				<!-- <input class="inpok" @click="djjqhq" type="text" style="text-align: right; width: 150px; color: red;"
					value="3天可约 >" disabled /> -->
				<view style="text-align: right; color: red;" @click="djjqhq" :value="keyue">{{ dayCount }}天可约 <text
						class="kuoyi">></text></view>
			</div>
		</div>

		<div class="daduo">
			<div class="input-group">
				<label class="password-label">服务价格:</label>
				<input class="inpok" type="text" id="fuwujiag" v-model="fuwujiag" placeholder="请填写服务价格" />
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">学历</label>
				<!-- <input class="inpok" @click="djhqnr" type="text" style="text-align: right; width: 250px;" value="初中 >"
					disabled /> -->
				<div class="kaoyb">
					<picker @change="bindPickerChange1" :value="index1" :range="array1">
						<view class="uni-input">{{ array1[index1] }} <text class="kuoyi">></text></view>
					</picker>
				</div>
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">等级</label>
				<!-- <input class="inpok" @click="djhqnr" type="text" style="text-align: right; width: 250px;" value="金牌 >"
					disabled /> -->
				<div class="kaoyb">
					<picker @change="bindPickerChange2" :value="index2" :range="array2">
						<view class="uni-input">{{ array2[index2] }} <text class="kuoyi">></text></view>
					</picker>
				</div>
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">星级</label>
				<!-- <input class="inpok" @click="djhqnr" type="text" style="text-align: right; width: 250px;" value="4星 >"
					disabled /> -->
				<div class="kaoyb">
					<picker @change="bindPickerChange3" :value="index3" :range="array3">
						<view class="uni-input">{{ array3[index3] }} <text class="kuoyi">></text></view>
					</picker>
				</div>
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">证书</label>
				<input class="inpok" type="text" style="text-align: right; width: 250px;" value="至少选择2项" disabled />
			</div>
			<div class="underline-div"></div>
			<uv-checkbox-group v-model="checkboxValue">
				<uv-checkbox :customStyle="{marginRight: '12px', marginBottom: '8px'}"
					v-for="(item, index) in checkboxList" :key="index" :label="item.name" :name="item.name"
					activeColor="green"></uv-checkbox>
			</uv-checkbox-group>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">属相:</label>
				<input class="inpok" type="text" id="shuxiang" v-model="shuxiang" placeholder="请填写属相" />
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">民族:</label>
				<input class="inpok" type="text" id="minzu" v-model="minzu" placeholder="请填写民族" />
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">年龄(岁):</label>
				<input class="inpok" type="text" id="nianl" v-model="nianl" placeholder="请填写年龄(岁)" />
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">经验(年):</label>
				<input class="inpok" type="text" id="jinyan" v-model="jinyan" placeholder="请填写经验(年)" />
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">籍贯:</label>
				<input class="inpok" type="text" id="jiguan" v-model="jiguan" placeholder="请填写籍贯" />
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">特点标签</label>
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<textarea class="inpok" type="text" id="tedian" v-model="tedian" style="height: 50px;"
					placeholder="请填写特点标签" />
			</div>
			<div class="underline-div"></div>
			<div class="tuppp" style="gap: 2px; margin-top: -15px;">
				<img src="/static/biq.png" style="height: 18px; width: 18px;" />
				<div style="color: #8d8d8d;">多个标签请用逗号分隔</div>
			</div>
			<div class="input-group" style="margin-top: 15px;">
				<label class="password-label">封面图片上传(必填)</label>
				<div style="color: #8d8d8d; font-size: 14px; margin-right: 40px;">(每张不超过10M)</div>
			</div>
			<div class="underline-div"></div>
			<div>
				<uni-file-picker v-model="imageValue" file-mediatype="image" mode="grid" :limit="1" @progress="progress"
					@success="success" @fail="fail" @select="select" @delete="remove" />
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<label class="password-label">介绍图集上传(必填)</label>
				<div style="color: #8d8d8d; font-size: 14px; margin-right: 40px;">(每张不超过10M)</div>
			</div>
			<div class="underline-div"></div>
			<div>
				<view class="example-body">
					<uni-file-picker v-model="imageValue1" file-mediatype="image" mode="grid" limit="8"
						@progress="progress" @success="success" @fail="fail" @select="select1" @delete="removes"
						title="最多选择8张图片"></uni-file-picker>
				</view>
			</div>
			<div class="input-group" style="margin-top: 30px;">
				<label class="password-label">详细介绍</label>
				<div style="margin-left: 155px;">{{ wordCount }}/5000</div>
			</div>
			<div class="underline-div"></div>
			<div class="input-group">
				<textarea class="inpok" maxlength="5000" type="text" style="height: 150px; width: 300px;"
					placeholder="请填写详细介绍" id="xiangxi" v-model="text" />
			</div>
		</div>
		<div>
			<button class="baocuen" @click="baochui">保存</button>
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog cancelText="取消" confirmText="确定" title="温馨提示" :content="nrtsk"
					@confirm="dialogConfirm"></uni-popup-dialog>
			</uni-popup>
		</div>
		<div style="height: 50px;"></div>
	</div>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		gonavigateTo
	} from '@/request/wx.js';
	import {
		updated,
		showed,
		shower,
		url,
		updataimgpath,
		delimgpaht,
		addurlpath,
		delurlpath,
		showurllist
	} from '@/request/api.js'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';

	const imageValue = ref([]);
	const imageValue1 = ref([]);
	// const checkbox1 = ref([]);
	const nrtsk = ref('');
	const alertDialog = ref(null);

	const biaoti = ref('');
	const fuwujiag = ref('');
	const shuxiang = ref('');
	const minzu = ref('');
	const nianl = ref('');
	const jinyan = ref('');
	const jiguan = ref('');
	const tedian = ref('');
	const keyue = ref([]);
	const dayCount = computed(() => keyue.value.length);

	const checkboxValue = ref([]); //'执业证书', '身份证'
	console.log(checkboxValue);
	const checkboxList = ref([{
			name: '背调合格',
			disabled: false
		},
		{
			name: '保证金已缴纳',
			disabled: false
		},
		{
			name: '身份证',
			disabled: false
		},
		{
			name: '健康证',
			disabled: false
		},
		{
			name: '体检报告',
			disabled: false
		},
		{
			name: '执业证书',
			disabled: false
		}
	]);
	// 上传图片方法
	const uploadImages = (file) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: url() + 'state/upload', // 服务器上传接口地址
				filePath: file, // 媒体文件路径
				name: 'file', // 必须填写的文件对应的 key，用于服务器端接收文件
				formData: {
					'user': 'test' // 需要额外上传的参数
				},
				success: function(uploadRes) {
					let response = uploadRes.data;
					try {
						let resData = JSON.parse(response);
						console.log(resData)
						resolve(resData); // 使用 Promise 解决（resolve）成功的结果
					} catch (e) {
						reject(e); // 如果解析失败，使用 Promise 拒绝（reject）错误
					}
				},
				fail: function(uploadErr) {
					reject(uploadErr); // 上传失败，使用 Promise 拒绝（reject）错误
				}
			});
		});
	};
	const select = async (e) => {
		console.log('选择文件：', e);
		try {
			const req = await uploadImages(e.tempFilePaths[0]);
			imageValue.value = {
				'url': url() + req.data.targetPath
			}
			const updateResult = await updataimgpath({
				'id': token,
				"imgpath": req.data.targetPath
			});
		} catch (error) {
			console.error('操作失败', error);
		}
	};
	//删除图片
	const remove = async (e) => {
		console.log(e)
		const url = e.tempFilePath
		const base = "http://localhost:8080/state/images/";
		const relativeUrl = url.substring(base.length);
		const req = await delimgpaht({
			'imgpath': relativeUrl,
			'id': token
		})
	};
	const select1 = async (e) => {
		console.log('选择文件：', e);
		// 将新选择的文件添加到imageValue1数组中
		//imageValue1.value = imageValue1.value.concat(e.tempFiles);
		const req = await uploadImages(e.tempFilePaths[0]);
		imageValue1.value = imageValue1.value.concat({
			'url': url() + req.data.targetPath
		})
		const reqs = await addurlpath({
			'sid': token,
			'urlpath': req.data.targetPath
		})
	};
	const removes = async (e) => {
		const url = e.tempFilePath
		const base = "http://localhost:8080/state/images/";
		const relativeUrl = url.substring(base.length);
		await delurlpath({
			'imgpath': relativeUrl
		})
	}
	const progress = (e) => {
		console.log('上传进度：', e);
	};

	const success = (e) => {
		console.log('上传成功');
	};

	const fail = (e) => {
		console.log('上传失败：', e);
	};

	const djhqnr = () => {
		console.log("获取");
	};

	const djjqhq = () => {
		console.log("获取日期排期");
		gonavigateTo(`/pages/home/index/given`);
	};

	const text = ref('');

	// 创建一个计算属性来计算字数
	const wordCount = computed(() => text.value.length);

	const array = ref(['不可取消', '随时可取消', '仅开始前可取消']);
	const index = ref(1);

	const array1 = ref(['小学', '初中', '高中', '大学', '其他']);
	const index1 = ref(1);

	const array2 = ref(['金牌', '银牌', '普通']);
	const index2 = ref(0);

	const array3 = ref(['1星', '2星', '3星', '4星', '5星', '6星']);
	const index3 = ref(3);

	// 事件处理函数
	const bindPickerChange = (e) => {
		console.log('picker发送选择改变，携带值为', e.detail.value);
		index.value = e.detail.value;
	};

	const bindPickerChange1 = (e) => {
		console.log('picker1发送选择改变，携带值为', e.detail.value);
		index1.value = e.detail.value;
	};

	const bindPickerChange2 = (e) => {
		console.log('picker2发送选择改变，携带值为', e.detail.value);
		index2.value = e.detail.value;
	};

	const bindPickerChange3 = (e) => {
		console.log('picker3发送选择改变，携带值为', e.detail.value);
		index3.value = e.detail.value;
	};

	const token = uni.getStorageSync('uid');
	console.log(token);

	//显示时间设置
	onShow(async (e) => {
		try {
			const ggb = {
				'sid': token
			};
			const response = await shower(ggb);

			console.log(response)
			const datsi = response.data.data;
			let yyy = '';
			for (const [index, item] of datsi.entries()) {
				// console.log('ID:', index + 1);
				console.log('ID:', item);
				console.log('ID:', item.date);
				yyy += item.date
			}
			// console.log(yyy)
			const dates = yyy.match(/(\d{4}-\d{2}-\d{2})/g) || [];
			keyue.value = dates;
		} catch (error) {
			console.error("请求失败:", error);
		}
	})
	let imgpathlist = []
	const baochui = () => {
		if (biaoti.value === '') {
			nrtsk.value = "[标题] 不能为空";
			alertDialog.value.open();
			return;
		}

		if (fuwujiag.value === '') {
			nrtsk.value = "请填写 [服务价格]";
			alertDialog.value.open();
			return;
		}

		if (checkboxValue.value.length === 0) {
			nrtsk.value = "请选择 [证书]";
			alertDialog.value.open();
			return;
		}

		if (checkboxValue.value.length < 2) {
			nrtsk.value = "[证书] 至少选择2项";
			alertDialog.value.open();
			return;
		}

		if (shuxiang.value === '') {
			nrtsk.value = "请填写 [属相]";
			alertDialog.value.open();
			return;
		}

		if (minzu.value === '') {
			nrtsk.value = "请填写 [民族]";
			alertDialog.value.open();
			return;
		}

		if (nianl.value === '') {
			nrtsk.value = "请填写 [年龄(岁)]";
			alertDialog.value.open();
			return;
		}

		if (jinyan.value === '') {
			nrtsk.value = "请填写 [经验(年)]";
			alertDialog.value.open();
			return;
		}

		if (jiguan.value === '') {
			nrtsk.value = "请填写 [籍贯]";
			alertDialog.value.open();
			return;
		}

		if (tedian.value === '') {
			nrtsk.value = "请填写 [特点标签]";
			alertDialog.value.open();
			return;
		}

		if (imageValue.value.length === 0) {
			nrtsk.value = "请上传 [封面图片]";
			alertDialog.value.open();
			return;
		}

		// if (imageValue1.value.length === 0) {
		// 	nrtsk.value = "请上传 [介绍图集]";
		// 	alertDialog.value.open();
		// 	return;
		// }

		if (text.value === '') {
			nrtsk.value = "请填写 [详细介绍]";
			alertDialog.value.open();
			return;
		}

		console.log("标题" + biaoti.value)
		console.log("取消设置" + index.value)
		console.log("预约时段排期设置" + keyue.value)
		console.log("服务价格" + fuwujiag.value)
		console.log("学历" + index1.value)
		console.log("等级" + index2.value)
		console.log("星级" + index3.value)
		console.log("证书" + checkboxValue.value)
		const str = checkboxValue.value + '';
		const arr = str.split(',');
		let i1 = 0;
		let i2 = 0;
		let i3 = 0;
		let i4 = 0;
		let i5 = 0;
		let i6 = 0;
		arr.forEach((item, index) => {
			console.log(`索引 ${index}: 值 "${item}"`);

			if (item.includes('背调合格')) {
				i1 = 1;
				console.log(`值 "${item}" 包含 "背调合格"`);
			} else if (item.includes('保证金已缴纳')) {
				i2 = 1;
				console.log(`值 "${item}" 包含 "保证金已缴纳"`);
			} else if (item.includes('身份证')) {
				i3 = 1;
				console.log(`值 "${item}" 包含 "身份证"`);
			} else if (item.includes('健康证')) {
				i4 = 1;
				console.log(`值 "${item}" 包含 "健康证"`);
			} else if (item.includes('体检报告')) {
				i5 = 1;
				console.log(`值 "${item}" 包含 "体检报告"`);
			} else if (item.includes('执业证书')) {
				i6 = 1;
				console.log(`值 "${item}" 包含 "执业证书"`);
			} else {
				console.log("数据错误")
			}
		});
		console.log("属相" + shuxiang.value)
		console.log("民族" + minzu.value)
		console.log("年龄" + nianl.value)
		console.log("经验" + jinyan.value)
		console.log("籍贯" + jiguan.value)
		console.log("特点标签" + tedian.value)
		console.log("封面图片" + imageValue.value)
		console.log("介绍图集" + imageValue1.value)
		console.log("详细介绍" + text.value)
		const u = {
			'id': token,
			'title': biaoti.value,
			'cancel': index.value,
			'price': fuwujiag.value,
			'education': index1.value,
			'cls': index2.value,
			'star': index3.value,
			'certificate': checkboxValue.value,
			'birth': shuxiang.value,
			'nation': minzu.value,
			'age': nianl.value,
			'suffer': jinyan.value,
			'natv': jiguan.value,
			'trait': tedian.value,
			'introduce': text.value,
			'tone': i1,
			'bail': i2,
			'card': i3,
			'maritime': i4,
			'health': i5,
			'practise': i6,
		};
		console.log(u);
		if (token === '') {
			console.log("未登录");
			return;
		}
		updated(u).then((res) => {
			uni.navigateTo({
				url: '/pages/home/index/index'
			});
		});
	};

	showed({
		'id': token
	}).then((res) => {
		console.log(res);
		console.log(res.data.data);
		let iiii = res.data.data;

		const itemsi = JSON.parse(iiii.certificate);
		console.log(iiii.certificate);

		biaoti.value = iiii.title;
		index.value = iiii.cancel;
		fuwujiag.value = iiii.price;
		index1.value = iiii.education;
		index2.value = iiii.cls;
		index3.value = iiii.star;
		checkboxValue.value = itemsi;
		shuxiang.value = iiii.birth;
		minzu.value = iiii.nation;
		nianl.value = iiii.age;
		jinyan.value = iiii.suffer;
		jiguan.value = iiii.natv;
		tedian.value = iiii.trait;
		text.value = iiii.introduce;
		if (iiii.imgpath != '') {
			imageValue.value = {
				url: url() + iiii.imgpath
			}
		}

		showurllist({
			'id': token
		}).then((req) => {
			console.log(req.data.data)
			// 创建一个新的对象数组，每个对象都包含一个 url 属性
			imageValue1.value = req.data.data.map(path => ({
				url: url() + path.urlpath // 假设 url() 函数返回基础 URL
			}));
		})
	});

	const dialogConfirm = () => {
		console.log('点击确认');
	};
</script>

<style scoped>
	.dialog,
	.yuie,
	.daduo {
		border: 1px solid #ccc;
		border-radius: 4px;
		padding: 20px;
		width: 82%;
		background-color: white;
		z-index: 1000;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		margin-left: 12px;
		margin-top: 30upx;
	}

	.yuie {
		background-color: #fef2ce;
	}

	.password-label::before {
		content: '*';
		color: red;
		/* 设置星号的颜色 */
		font-weight: bold;
		vertical-align: middle;
		/* 确保星号与文本垂直居中对齐 */
		font-size: 1em;
		/* 确保星号的大小与文本一致 */
	}

	/* 确保 label 的行高不会影响伪元素的对齐 */
	.password-label {
		line-height: 1;
		/* 设置行高为1，减少行高的影响 */
		display: inline-block;
		/* 使 label 可以包含伪元素 */
		font-weight: bold;
		margin-right: 8px;
	}

	.inpok {}

	.inpok:focus {
		border: none;
		outline: none;
	}

	.input-group {
		display: table;
		/* 使用table布局 */
		width: 100%;
		/* 使容器宽度为100% */
		table-layout: auto;
		/* 表格布局自动调整 */
		margin-left: auto;
		/* 将容器居中对齐 */
		margin-right: auto;
		/* 将容器居中对齐 */
	}

	.input-group .password-label,
	.input-group .kaoyb {
		display: table-cell;
		/* 使子元素以表格单元格的形式显示 */
		vertical-align: middle;
		/* 垂直居中对齐 */
	}

	.input-group .kaoyb {
		width: 220px;
		/* 设置picker的宽度 */
	}

	.underline-div {
		border-bottom: 1px solid #9e9e9e;
		/* 1px黑色虚线作为下划线 */
		width: 100%;
		/* 设置下划线的长度为容器宽度的50% */
		height: 0;
		/* 由于设置了下划线，需要将div的高度设置为0 */
		margin: 20px auto;
		/* 居中显示下划线 */
	}

	.example-body {
		padding: 10px;
		padding-top: 0;
	}

	.baocuen {
		width: 85%;
		border: none;
		background-color: #149fad;
		color: white;
		border-radius: 4px;
		cursor: pointer;
		font-size: 16px;
		margin-top: 35px;
		clip-path: inset(0 round 55upx 55upx 55upx 55upx);
	}

	.kuoyi {
		color: #8d8d8d;
		font-size: 20px;
	}

	.kaoyb {
		text-align: right;
	}

	.tuppp {
		display: flex;
		/* 使用Flexbox布局 */
		align-items: center;
		/* 垂直居中对齐 */
		gap: 2px;
		/* 设置子元素之间的间距 */
		margin-top: -15px;
		/* 容器的上边距 */
	}
</style>